package com.ysx.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.Map;

/**
 * @author yyj
 * @date 2019/5/18
 */
@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("test")
    public String test(String name) {
//        ServiceInstance serviceInstance = loadBalancerClient.choose("ysx-nacos-provider");
//        URI uri = serviceInstance.getUri();
//        return restTemplate.getForObject(uri + "/name?name=" + name, String.class);
        RibbonLoadBalancerClient.RibbonServer ribbonServer = (RibbonLoadBalancerClient.RibbonServer) loadBalancerClient.choose("ysx-nacos-provider");
        NacosServer nacosServer = (NacosServer) ribbonServer.getServer();
        Map<String, String> metadata = nacosServer.getMetadata();
        System.out.println("metadata:" + metadata);
        URI uri = ribbonServer.getUri();
//        return restTemplate.getForObject("http://ysx-nacos-provider/name?name=" + name, String.class);
        return restTemplate.getForObject(uri + "/name?name=" + name, String.class);

    }
}
